/**
 * Created by Jackie.Chen on 2016/12/4.
 */

var userList = function () {
    /*基础配置*/
    var el = 'body';
    var addLay = null,updateLay = null;
    var searchObj = {
        username:'',
        state:'',
        status:'',
        startTime:'',
        endTime:'',
        page: 1,
        pageSize: 10
    };
    var validateCong = {
        rules: {
            mobile: {
                required: true,
                isTrueTel:true
            }
        },
        messages: {
            mobile: {
                required: "请输入手机号",
            }
        }
    }
    //添加校验规则手机号
    jQuery.validator.addMethod("isTrueTel", function(value, element) {
        var tel = /^1[3|4|5|7|8][0-9]{9}$/;
        return this.optional(element) || (tel.test(value));
    }, "手机号码格式错误！");

    //重置
    function doReset(){
        $("#username").val("");
        $("#state").val("");
        $('#searchTimeRange').val("");
        $('#startDate').val("");
        $('#endDate').val("");
    }

    /*操作*/
    function doSearch() {
        var username = $("#username").val();
        var state= $("#state").attr('data');
        var startTime = $('#startDate').val();
        var endTime = $('#endDate').val();
        searchObj.username = username || '';
        searchObj.state = state || '';
        searchObj.startTime = startTime || '';
        searchObj.endTime = endTime || '';
        searchObj.page = 1;  //reset
        renderPages(true);
    }

    /*禁用该用户*/
    function offLine() {
        var $this = $(this),
            userid = $this.parent().attr('data');
        var deleteLay = layer.confirm('是否禁用此用户？', {
            btn: ['是', '否'] //按钮
        }, function () {
            if($('#userList').find('tbody tr').length == 1 && searchObj.page !== 1){ //当当前只有一页的时候
                searchObj.page = searchObj.page - 1;
            }
            ajaxCommonFun({
                type: 'GET',
                url: '/offLine.do?userid=' + userid,
                success: function (t) {
                    if (t.status == 'ERROR') {
                        layer.msg(t.message);
                    }else {
                        layer.close(deleteLay);
                        layer.msg(t.result);
                        renderPages(true);
                    }
                }
            });
        });

    }
    /**启用该用户*/
    function onLine() {
        var $this = $(this),
            userid = $this.parent().attr('data');
        var deleteLay = layer.confirm('是否确认启用用户？', {
            btn: ['是', '否'] //按钮
        }, function () {
            if($('#userList').find('tbody tr').length == 1 && searchObj.page !== 1){ //当当前只有一页的时候
                searchObj.page = searchObj.page - 1;
            }
            ajaxCommonFun({
                type: 'GET',
                url: '/onLine.do?userid=' + userid,
                success: function (t) {
                    if (t.status == 'ERROR') {
                        layer.msg(t.message);
                    }else {
                        layer.close(deleteLay);
                        layer.msg(t.result);
                        renderPages(true);
                    }
                }
            });
        });
    }
    /*end操作*/

    /*
    * 数据详情显示
    */
    function details() {
        var $this = $(this),
            userid = $this.parent().parent().attr("data");
        getHtmlByUrl({
            url: "/getDetails.do?userid=" + userid,
            success: function (res) {
                if (res.status == 'ERROR') {
                    layer.msg(res.message);
                } else {
                    layer.open({
                        type: 1,
                        title: '',
                        btn: ['关闭'],
                        area: ['620px', '440px'],
                        content: res, // $('#dataTableDetail'),
                        btn1: function (index) {
                            layer.close(index);
                        }
                    });
                }
            }

        });

    }

    /*编辑数据*/
    function edit() {
        var $this = $(this),
            userid = $this.parent().parent().attr('data');
        getHtmlByUrl({
            url: "/edit.html?id=" + userid,
            success: function (res) {
                if (res.status == 'ERROR') {
                    layer.msg(res.message);
                } else {
                    updateLay = layer.open({
                        type: 1,
                        title: '',
                        area: ['620px', '360px'],
                        content: res,
                        btn: ['确定', '取消'],
                        btn1: function () {
                            $('#modifyForm').validate(validateCong);
                            if ($('#modifyForm').valid()) {
                                var dataparam = {
                                    "userid": userid,
                                    "mobile": $("#mobile").val()
                                };
                                ajaxCommonFun({
                                    type: 'POST',
                                    url: '/updateUserInfo.do',
                                    data: dataparam,
                                    success: function (t) {
                                        if (t.status == 'ERROR') {
                                            layer.msg(t.message);
                                        } else {
                                            renderPages(true);
                                            layer.close(updateLay);
                                            layer.msg(t.result);
                                        }
                                    }
                                });
                            }
                        },
                    });
                }
            }
        });
    }


    function renderPages(isFirst) {
        var url = '/getlist.do', isAdd = false;
        getHtmlByUrl({
            url: url,
            data:searchObj,
            success: function (res) {
                $("#userList").html(res);
                if(isFirst){
                    buildPageArea();
                }
            }
        });
    }
    /*end页面初始化和事件绑定*/


    function getOptionValue(e){
        var $me = $(this);
        $(this).parents('.dropdown-menu').siblings('.dropdown-toggle').removeClass('error').siblings('.error').remove();
        $me.parents('.dropdown-menu').siblings('.dropdown-toggle').val($me.find('a').text());
        $me.parents('.dropdown-menu').siblings('.dropdown-toggle').attr("data",$me.attr("data"));
    }
    /*分页*/
    function doChangePage(num) {
        searchObj.page = num;
        renderPages();
    }
    function buildPageArea() {
        var pageAllCount = $('#pageAllCount').val(),
            totalPage = Math.ceil(pageAllCount/searchObj.pageSize);
        laypage({
            cont: 'pageD',
            pages: totalPage,//totalPage
            curr: searchObj.page,
            totalCount:pageAllCount,
            skin: '#338af9',
            jump: function(obj, first){
                if(!first){
                    doChangePage(obj.curr);
                }
            }
        });
    }
    /*end分页*/
    /*页面初始化和事件绑定*/
    function bindEvents() {
        $(el).undelegate()
            .delegate('.dropdown-menu li','click',getOptionValue)
            .delegate('#searchBtn','click',doSearch)
            .delegate('a[name=on]','click',onLine)
            .delegate('a[name=off]','click',offLine)
            .delegate('a[name=edit]','click',edit)
            .delegate('#reset','click',doReset)
            .delegate('a[name=detail]','click',details);
    }

    /*页面初始化*/
    function init() {
        renderPages(true);
        bindEvents();
        /**日历*/
        $('#searchTimeRange').daterangepicker();
        $('#searchTimeRange').on('apply.daterangepicker',function(ev,picker){
            $("#startDate").val(picker.startDate.format('YYYY-MM-DD'));
            $("#endDate").val(picker.endDate.format('YYYY-MM-DD'));

        });

        /*日历end*/
    }
    /*end 页面初始化*/
    init();
};
